import React from 'react'
import BaseComponent from 'basecomponent'
import LinkNavbar from 'link-navbar'
import AntTable from 'anttable'
import FuncButton from "func-button";
import apis from 'apis'
import {withRouter} from 'react-router'
import './style.scss'
import {Form, Select, Cascader} from 'antd';
import SearchDiv from 'search-div'
import {universityTypes} from 'utils/staticType'
const Option = Select.Option;
const FormItem = Form.Item
let searchText = ''

class Company extends BaseComponent {
  constructor() {
    super(...arguments);
    this.state= {
      universityData: [],
      currentPage: 1,
      pageSize: 10,
      provinceData: [],
      cityData: [],
      selectedRows: []
    }
  }
  componentDidMount() {
    this.getUniversityList(null);
    this.getProvinceInfo();
  }

  getUniversityList(tag){
    this.universityRP && this.universityRP.request.abort()
    this.universityRP = apis.university.getUniversityList(null, null, tag);
    this.registerRequest(this.universityRP.request);
    this.universityRP.promise
      .then((res)=>{
        let data = res.Data || []
        data.map((item) => {
          let tags = item.Tags.split('|')
          item['levelFir'] = tags[0]
          item['batch'] = tags[1]
          item['addressFir'] = tags[2]
          item['category'] = tags[3]
        })
        res.Data&&this.setState({universityData: data});
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }


  getProvinceInfo() {
    this.getProviceRP = apis.address.getProvince();
    this.registerRequest(this.getProviceRP.request);
    this.getProviceRP.promise
      .then((res) => {
        let data = res.Data || []
        let provinceData = data.map(function (item) {
          return {
            value:JSON.stringify(item),
            label:item.Name,
            isLeaf:false
          }
        })
        this.setState({provinceData: provinceData});
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  loadCity(selectedOptions){
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    this.getCityRP && this.getCityRP.request.abort();
    this.getCityRP = apis.address.getCity(JSON.parse(targetOption.value).Id);
    this.registerRequest(this.getCityRP.request);
    this.getCityRP.promise
      .then((res) => {
        let data = res.Data || [];
        targetOption.loading = false;
        targetOption.children = data.map(function (item) {
          return{
            label:item.Name,
            value:JSON.stringify(item)
          }
        })
        this.setState({...this.state.provinceData})
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleLevelSelect(value) {
    if (value) {
      this.props.form.setFieldsValue({
        Batch: undefined,
        Category: undefined,
        Area: undefined
      })
      this.getUniversityList(value)
    }else{
      this.getUniversityList(null)
    }
  }
  handleBatchSelect(value) {
    if (value) {
      this.props.form.setFieldsValue({
        Level: undefined,
        Category: undefined,
        Area: undefined
      })
      this.getUniversityList(value)
    }else{
      this.getUniversityList(null)
    }
  }

  handleOnChange(value) {
    if (value && value.length > 1) {
      this.props.form.setFieldsValue({
        Level: undefined,
        Batch: undefined,
        Category: undefined
      })
      this.getUniversityList(JSON.parse(value).Name)
    }else{
      this.getUniversityList(null)
    }
  }
  handleCategorySelect(value) {
    if (value) {
      this.props.form.setFieldsValue({
        Level: undefined,
        Batch: undefined,
        Area: undefined
      })
      this.getUniversityList(value)
    }else{
      this.getUniversityList(null)
    }
  }
  searchChange(value) {
    this.props.form.setFieldsValue({
      Level: undefined,
      Batch: undefined,
      Area: undefined,
      Category: undefined
    })
    searchText = value
    if (!value || value.length <= 0){
      this.getUniversityList(null)
    }
  }
  handleSearchButton() {
    this.getUniversityList(searchText)
  }

  topCompany(text,record){
    let universityData = {}
    if(record.Order && record.Order === 1){
      universityData = Object.assign({}, record, {Order: 0})
    }else{
      universityData = Object.assign({}, record, {Order: 1})
    }
    this.reviseUniversityRP && this.reviseUniversityRP.request.abort()
    this.reviseUniversityRP = apis.university.reviseUniversity(universityData.Id, universityData)
    this.registerRequest(this.reviseUniversityRP.request)
    this.reviseUniversityRP.promise
      .then((res) => {
        alert('成功')
        this.getUniversityList()
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  watchCompany(text,record){
    let path={
      pathname:'/home/revise/university',
      query:{
        Id:record.Id,
      },
      state:{
        revise: false,
      }
    };
    this.props.router.push(path);
  }

  deleteCompany(text,record){
    let data = this.state.universityData
    this.deleteURP = apis.university.deleteUniversity(record.Id);
    this.registerRequest(this.deleteURP.request);
    this.deleteURP.promise
      .then((res) => {
        if(res === 'delete success'){
          data.forEach((item, index) => {
            if(item.Id === record.Id){
              data.splice(index,1)
              this.setState({
                universityData: data
              })
              alert('删除成功')
            }
          })
        }else{
          alert('删除失败')
        }
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  render() {
    const {children} = this.props;
    const {universityData,currentPage,pageSize,provinceData,selectedRows} = this.state;
    const columns = [{
      title: '学校名称',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '学校级别',
      dataIndex: 'levelFir',
      colSpan: 2,
    },
      {
        title: '学校级别',
        dataIndex: 'levelSec',
        colSpan: 0,
      },
      {
        title: '学校批次',
        dataIndex: 'batch',
        key: 'batch',
      },
      {
        title:'学校区域',
        dataIndex:'addressFir',
        colSpan:2,
      },
      {
        title:'学校区域',
        dataIndex:'addressSec',
        colSpan:0,
      },

      {
        title:'学校类别',
        dataIndex:'category',
        key:'category'
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
          <a onClick={()=>{this.topCompany(text,record)}}>
            {record.Order && record.Order === 1 ? '取消置顶' : '置顶'}
          </a>
            <span className="ant-divider"/>
          <a onClick={()=>{this.watchCompany(text,record)}}>查看</a>
          <span className="ant-divider"/>
          <a onClick={()=>{this.deleteCompany(text,record)}}>
            删除
          </a>
        </span>
        ),
      }];

    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;

    return (
      <div className={'sem-main-content'}>
        <div className={'class-company-page'}>
          <LinkNavbar props={this.props}/>
          {children ? children :
            <div className={'class-company-content'}>
              <FuncButton wrapperName={'class-company-FucBtn'}
                          leftText={'添加'}
                          leftTo={{pathname:'/home/add/university/',query:{Id:-1}}}
                          showRight={false}
              />
              <Form hideRequiredMark={true}>
                <div className={'class-select-div'}>
                  <FormItem style={{marginTop: 'auto', marginBottom:'auto'}}>
                    {getFieldDecorator('Level')(
                      <Select className={'level-select margin-left'}
                              onChange={this.handleLevelSelect.bind(this)}
                              placeholder={'学校级别'}
                              size={'large'}
                              filterOption={false}
                              allowClear={true}
                              notFoundContent={'-'}>
                        <Option key={'双一流'}>{'双一流'}</Option>
                        <Option key={'985'}>{'985'}</Option>
                        <Option key={'211'}>{'211'}</Option>
                      </Select>
                    )}
                  </FormItem>
                  <FormItem style={{marginTop: 'auto', marginBottom:'auto'}}>
                    {getFieldDecorator('Batch')(
                      <Select className={'batch-select'}
                              placeholder={'学校批次'}
                              onChange={this.handleBatchSelect.bind(this)}
                              size={'large'}
                              allowClear={true}
                              notFoundContent={'-'}>
                        <Option key={'本科'}>{'本科'}</Option>
                        <Option key={'专科'}>{'专科'}</Option>
                      </Select>
                    )}
                  </FormItem>
                  <FormItem style={{marginTop: 'auto', marginBottom:'auto'}}>
                    {getFieldDecorator('Area')(
/*                      <Cascader className={'area-select'}
                                options={provinceData}
                                onChange={this.handleOnChange.bind(this)}
                                loadData={this.loadCity.bind(this)}
                                size={'large'}
                                placeholder={'学校区域'}
                                notFoundContent={'-'}>
                       </Cascader>*/
                      <Select className={'batch-select'}
                              placeholder={'学校区域'}
                              onChange={this.handleOnChange.bind(this)}
                              size={'large'}
                              allowClear={true}
                              notFoundContent={'-'}>
                        {provinceData.map((item) => {
                          return <Option key={item.value}>{item.label}</Option>
                        })}
                      </Select>
                    )}
                  </FormItem>
                  <FormItem style={{marginTop: 'auto', marginBottom:'auto'}}>
                    {getFieldDecorator('Category')(
                      <Select className={'category-select'}
                              onChange={this.handleCategorySelect.bind(this)}
                              placeholder={'学校类别'}
                              size={'large'}
                              allowClear={true}
                              notFoundContent={'-'}>
                        {
                          universityTypes.map((item, index) => {
                            return <Option key={index} value={item}>{item}</Option>
                          })
                        }
                      </Select>
                    )}
                  </FormItem>
                  <FormItem style={{marginTop: 'auto', marginBottom:'auto', marginLeft:'auto'}}>
                    {getFieldDecorator('Search')(
                      <SearchDiv className={'search'}
                                 inputChange={this.searchChange.bind(this)}
                                 buttonClick={this.handleSearchButton.bind(this)}
                      />
                    )}
                  </FormItem>
                </div>
              </Form>
              <AntTable columns={columns} data={universityData} 
                        pagination={true} currentPage={currentPage} pageSize={pageSize}
                        onChange={(pagination)=>{
                          this.setState({
                            currentPage:pagination.current,
                            pageSize:pagination.pageSize,
                          })
                        }}/>
            </div>}
        </div>
      </div>
    );
  }
}

module.exports = Form.create()(withRouter(Company));
